package com.macro.mall.boot.wechat.mp;

import com.macro.mall.boot.wechat.props.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号配置
 *
 * @author xuyanjun
 * @date 2019-07-09
 */
@Slf4j
@Configuration
public class WxMpConfig {

    /**
     * 微信服务
     */
    private static Map<Integer, WxMpService> WX_MP_SERVICE_MAP = new HashMap<>();


    /**
     * 获取微信服务
     *
     * @param businessAppId 业务AppId
     * @return 微信服务
     */
    public static WxMpService getWxMpServiceByBusinessAppId(int businessAppId) {
        Assert.isTrue(businessAppId > 0, "业务AppId不能为空。");

        WxMpService wxMaService = WX_MP_SERVICE_MAP.get(businessAppId);
        if (wxMaService == null) {
            log.error("未配置对应的业务appId:" + businessAppId);

            throw new IllegalArgumentException("未配置对应的业务appId。");
        }

        return wxMaService;
    }

    @Profile(value = {"dev", "test"})
    @Bean
    public Inner wxMpPropertiesDev() {
        WxMpProperties wxMpProperties = new WxMpProperties();
        wxMpProperties.setAppId("wx8623ac1cbaaf7a3d")
                .setSecret("248998d986db1daeae462c0c370db87e")
                .setToken("j7t86Ipf888uAMIii5FiTi559A6zDffT")
                .setAesKey("o7CC29uUUAU9699Z3a55U46R34434auac60L4lu0C20");

        buildMpService(10001, wxMpProperties);

        return new Inner();
    }

    @Profile(value = {"prod"})
    @Bean
    public Inner wxMpPropertiesPro() {
        WxMpProperties wxMpProperties = new WxMpProperties();
        wxMpProperties.setAppId("wx8623ac1cbaaf7a3d")
                .setSecret("248998d986db1daeae462c0c370db87e")
                .setToken("xuyanjunisagoodboy")
                .setAesKey("aRXINnmagPsSmpQeSgUAU7luxFyUzZkKxAV5NvZRWQv");

        buildMpService(10001, wxMpProperties);

        return new Inner();
    }

    private void buildMpService(int appId, WxMpProperties wxMpProperties) {
        WxMpInRedisConfig wxMpInRedisConfig=new WxMpInRedisConfig(wxMpProperties.getAppId());
        wxMpInRedisConfig.setAppId(wxMpProperties.getAppId());
        wxMpInRedisConfig.setSecret(wxMpProperties.getSecret());
        wxMpInRedisConfig.setAesKey(wxMpProperties.getAesKey());
        wxMpInRedisConfig.setToken(wxMpProperties.getToken());

        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpInRedisConfig);

        WX_MP_SERVICE_MAP.put(appId, wxMpService);
    }

    private static class Inner {

    }
}
